from news_2.src.main.store.web_state import *
from news_2.src.main.utils.file_tool import read_json_file


class Store:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(Store, cls).__new__(cls)
        return cls._instance

    # 初始化状态，并接受初始状态
    def __init__(self, initial_state=None):
        if not hasattr(self, '_initialized'):
            self.state = initial_state or {}
            self.mutations = {}
            self.actions = {}
            self._initialized = True

    # 触发突变，修改状态。
    def commit(self, mutation_name, *args):
        if mutation_name in self.mutations:
            self.mutations[mutation_name](self.state, *args)
        else:
            raise ValueError(f"Mutation '{mutation_name}' not found")

    # 执行异步操作。
    def dispatch(self, action_name, *args):
        if action_name in self.actions:
            return self.actions[action_name](self, *args)
        else:
            raise ValueError(f"Action '{action_name}' not found")

    # 注册突变函数
    def register_mutation(self, name, mutation):
        self.mutations[name] = mutation

    # 注册操作函数。
    def register_action(self, name, action):
        self.actions[name] = action


html_data = read_json_file("../resources/html_data.json")


def get_store():
    app_store = Store(html_data)

    # 注册突变和操作
    app_store.register_mutation('add_web_table', add_web_table)
    app_store.register_mutation('update_web_table_by_key', update_web_table_by_key)
    app_store.register_action('get_web_table', get_web_tables)
    app_store.register_action('get_web_table_by_key', get_web_table_by_key)

    return app_store
